package com.example.utils;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import reactor.core.publisher.Flux;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;

/**
 * 日志拦截器，用于记录访问的参数
 * @author hipop
 */
public class RequestLoggingInterceptor extends ServerHttpRequestDecorator {

    /**
     * 请求中的body数据,听说StringBuffer线程安全
     */
    public static StringBuffer bodyData;

    public RequestLoggingInterceptor(ServerHttpRequest delegate) {
        super(delegate);
    }

    @Override
    public Flux<DataBuffer> getBody() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        return super.getBody().doOnNext(dataBuffer -> {

            // 记录请求body的前2048个字符串
            int i = dataBuffer.readableByteCount();
            int len = i > 2048 ? 2048 : i;
            ByteBuffer byteBuffer = dataBuffer.asByteBuffer(0, len).asReadOnlyBuffer();
            try {
                Channels.newChannel(baos).write(byteBuffer);
                bodyData = new StringBuffer(new String(baos.toByteArray(), StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
